package com.woniuxy.carlife.minio;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author fx
 * @ClassName:MinioTemplate
 * @Description: minio上传文件模板
 * @date 2021/4/9 22:01
 **/
public class MinioTemplate {

   private MinioConfig mc;

   private MinioClient client;

   public  MinioTemplate(MinioConfig mc){
      this.mc=mc;
      this.client=MinioClient.builder()
              .endpoint(mc.getEndpoint())
              .credentials(mc.getAccessKey(),
                      mc.getSecretKey()).build();
   }

   /**
    * 功能描述〈上传文件方法〉
    * @author:fx
    * @param: @param null:
    * @return:
    * @Date 2021/4/9 22:32
    * @throws
    */
   public String uploadFile(String fileName, String bucketName, InputStream stream, Long size, String contentType) {
      PutObjectArgs poa = PutObjectArgs.builder()
              .object(fileName).bucket(bucketName).stream(stream, size, mc.getPartsize())
              .contentType(contentType)
              .build();
      try {
         client.putObject(poa);
         return mc.getEndpoint() + "/" + bucketName + fileName;
      } catch (InvalidKeyException | ErrorResponseException | InsufficientDataException |
              InternalException | InvalidResponseException |
              NoSuchAlgorithmException | ServerException | XmlParserException |
              IOException e) {
         e.printStackTrace();
         throw new RuntimeException("上传失败");
      }
   }

   /**
    * 功能描述〈删除方法〉
    * @author:fx
    * @param: @param null:
    * @return:
    * @Date 2021/4/9 22:46
    * @throws
    */
   public boolean deleteFile(String figeName, String bucketName) {
      try {
         RemoveObjectArgs roa = RemoveObjectArgs.builder().bucket(bucketName).object(figeName).build();
         client.removeObject(roa);
         return true;
      } catch (InvalidKeyException | ErrorResponseException | InsufficientDataException | InternalException |
              InvalidResponseException | NoSuchAlgorithmException | ServerException | XmlParserException | IOException e) {
         e. printStackTrace();
         throw new RuntimeException( "删除失败");
      }
   }
}
